import 'package:flutter/material.dart';
import '../services/storage.dart';
import 'dart:convert';
class Cart with ChangeNotifier{
  List  _cartList = [];
  bool _isCheckAll = true;
  double _allPrice = 0;
  List get cartList => this._cartList;
  bool get isCheckAll => this._isCheckAll;
  double get allPrice => this._allPrice;
  Cart(){
    this.init();
  }
  // 初始化的时候获取购物车的数据
  init() async{
    try {
      List cartListData = json.decode(await Storage.getString('cartList'));
      this._cartList = cartListData;
      computeAllPrice();
      notifyListeners();
    } catch (e) {

    }
  }

  updateCartList(){
    this.init();
  }
  addList(value){
    notifyListeners();
  }

  changeCount(){
    Storage.setString('cartList',json.encode(this._cartList));
    computeAllPrice();
    notifyListeners();
  }

  checkAll(value){
    this._isCheckAll = value;
    this._cartList.forEach((e){
      e['checked'] = value;
    });
    computeAllPrice();
    notifyListeners();
  }
  isCheckAlls(){
    bool check = true;
    for (var i = 0; i < this._cartList.length; i++) {
        if(!this._cartList[i]['checked']){
           check = false;
           break;
        }
    }
    return check;
  }
  itemChage(){
    this._isCheckAll = this.isCheckAlls();
    computeAllPrice();
    notifyListeners();
  }

  computeAllPrice(){
    double price = 0;
    for (var i = 0; i < this._cartList.length; i++) {
      if(this._cartList[i]['checked']){
          price += this._cartList[i]['price'] * this._cartList[i]['count'];
      }
    }
    this._allPrice = price;
    notifyListeners();
  }

  removeItem(){
    print("object");
    List tempList = [];
    for (var i = 0; i < this._cartList.length; i++) {
        if(!this._cartList[i]['checked']){
           tempList.add(this._cartList[i]);
        }
    }  
    this._cartList = tempList;
    changeCount();
  }
}